﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using TWS.Client;

public partial class admin_ChiTietSanPham : BaseAdminPage
{

    protected void repListCha_OnItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            LoaiSanPhamHelper lspHP = new LoaiSanPhamHelper();
            Repeater repCon = ((Repeater)e.Item.FindControl("repCon"));
            repCon.DataSource = (lspHP.LoadLoaiSanPhamCon(Convert.ToInt32((((DataRowView)e.Item.DataItem)["LoaiSanPhamID"]))));
            repCon.DataBind();
        }
    }

    protected void ddlLoaiCha_OnSelectedIndexChanged(object sender, EventArgs e)
    {
        int id = Convert.ToInt32(ddlLoaiCha.SelectedValue);
        LoaiSanPhamDataSet lspDS = new LoaiSanPhamHelper().LoadLoaiSanPhamCon(id);
        ddlLoaiCon.DataSource = lspDS.LoaiSanPham;
        ddlLoaiCon.DataTextField = "TenLoaiSanPham";
        ddlLoaiCon.DataValueField = "LoaiSanPhamID";
        ddlLoaiCon.DataBind();
    }

    protected void btnOK_OnClick(object sender, EventArgs e)
    {
        //Page.Validate();
        //if (!Page.IsValid) return;
        //SanPhamHelper spHP = new SanPhamHelper();
        //SanPhamDataSet spDS = new SanPhamDataSet();
        //SanPhamDataSet.SanPhamRow sanphammoi = spDS.SanPham.NewSanPhamRow();
        //sanphammoi.TenSanPham = txtTenSanPham.Text;
        //sanphammoi.LoaiSanPham = Convert.ToInt32(ddlLoaiCon.SelectedValue);
        //sanphammoi.HangSanXuat = txtHangSanXuat.Text;
        //sanphammoi.ChungLoai = txtChungLoai.Text;
        //sanphammoi.Gia = Convert.ToInt32(txtGia.Text);
        //////UploadImage();
        //if (txtHinhAnh.Text == string.Empty)
        //{
        //    txtHinhAnh.Text = "noimage.jpg";
        //}
        //sanphammoi.HinhAnh = txtHinhAnh.Text;
        //sanphammoi.SanPhamMoi = ckSanPhamMoi.Checked;
        //sanphammoi.ThuTu = Convert.ToInt32(txtThuTu.Text);
        //sanphammoi.NgayDang = DateTime.Now;

        //sanphammoi.TongQuan = txtTongQuan.Text;
        //sanphammoi.ThongSoKyThuat = txtThongSo.Text;
        //sanphammoi.Album = txtAlbum.Text;
        //spDS.SanPham.AddSanPhamRow(sanphammoi);
        //spHP.SaveSanPham(spDS);
        //RedirectPage(Request.RawUrl, true);
        SaveData();
    }

    private SanPhamDataSet m_SanPhamDataSet;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            LoadData();
            try
            {
                string mode = Request.QueryString["mode"];
                bool isNew = false;
                if (mode != "edit")
                {
                    isNew = true;
                }
                string key = Request.QueryString["id"];
                if (!isNew)
                {
                    if (key != null && key != string.Empty)
                    {
                        LoadData(key);
                    }
                }
                else
                {
                    m_SanPhamDataSet = new SanPhamDataSet();

                    SanPhamDataSet.SanPhamRow danhMuc = m_SanPhamDataSet.SanPham.NewSanPhamRow();
                    danhMuc.SanPhamID = -1;
                    danhMuc.HinhAnh = "noimage.jpg";

                    m_SanPhamDataSet.SanPham.AddSanPhamRow(danhMuc);
                    Session[this.Request.Url.AbsolutePath.ToString() + "_" + "Data"] = m_SanPhamDataSet;

                    txtHinhAnh.Text = "noimage.jpg";
                }

            }
            catch (Exception ex)
            {
                //DisplayMesseage(ex.Message);
                this.RedirectPage("pgError.aspx", false);
            }
        }
    }
    private void LoadData()
    {
        LoaiSanPhamDataSet lspDS = new LoaiSanPhamHelper().LoadLoaiSanPhamCha();
        ddlLoaiCha.DataSource = lspDS.LoaiSanPham;
        ddlLoaiCha.DataTextField = "TenLoaiSanPham";
        ddlLoaiCha.DataValueField = "LoaiSanPhamID";
        ddlLoaiCha.DataBind();
        ddlLoaiCha.Enabled = false;
        
    }

    private void LoadData(string benhLyId)
    {
        int itemId;
        if (int.TryParse(benhLyId, out itemId))
        {
            SanPhamHelper helper = new SanPhamHelper();
            SanPhamDataSet tempDs = helper.LoadSanPham(itemId);


            SanPhamDataSet.SanPhamRow danhMuc = tempDs.SanPham.FindBySanPhamID(itemId);
            m_SanPhamDataSet = new SanPhamDataSet();
            m_SanPhamDataSet.SanPham.ImportRow(danhMuc);

            Session[this.Request.Url.AbsolutePath.ToString() + "_" + "Data"] = m_SanPhamDataSet;

             txtTenSanPham.Text=danhMuc.TenSanPham;
             lbTenSanPham.Text = danhMuc.TenSanPham;
             LoaiSanPhamHelper lspHP = new LoaiSanPhamHelper();
             LoaiSanPhamDataSet lspDS = lspHP.GetLoaiSanPhamCha(danhMuc.LoaiSanPham);
             if (lspDS.LoaiSanPham.Rows.Count>0)
             {
                 ddlLoaiCha.SelectedValue = lspDS.LoaiSanPham[0].LoaiSanPhamID.ToString();
                 int id = Convert.ToInt32(ddlLoaiCha.SelectedValue);
                 LoaiSanPhamDataSet lspDSCon = new LoaiSanPhamHelper().LoadLoaiSanPhamCon(id);
                 ddlLoaiCon.DataSource = lspDSCon.LoaiSanPham;
                 ddlLoaiCon.DataTextField = "TenLoaiSanPham";
                 ddlLoaiCon.DataValueField = "LoaiSanPhamID";
                 ddlLoaiCon.DataBind();
             }
             if (!danhMuc.IsLoaiSanPhamNull()) ddlLoaiCon.SelectedValue = danhMuc.LoaiSanPham.ToString();
             if (!danhMuc.IsHangSanXuatNull()) txtHangSanXuat.Text = danhMuc.HangSanXuat;
             if (!danhMuc.IsChungLoaiNull()) txtChungLoai.Text = danhMuc.ChungLoai;
             if (!danhMuc.IsGiaNull  ()) txtGia.Text = danhMuc.Gia.ToString();
             if (!danhMuc.IsSanPhamMoiNull ()) ckSanPhamMoi.Checked = danhMuc.SanPhamMoi;
             if (!danhMuc.IsThuTuNull()) txtThuTu.Text = danhMuc.ThuTu.ToString();

             if (!danhMuc.IsTongQuanNull()) txtTongQuan.Text = danhMuc.TongQuan;
             if (!danhMuc.IsThongSoKyThuatNull()) txtThongSo.Text = danhMuc.ThongSoKyThuat;
             if (!danhMuc.IsAlbumNull()) txtAlbum.Text = danhMuc.Album;


            //if (!BaiVietHay.IsHinhAnhNull()) {
             if (!danhMuc.IsHinhAnhNull()) txtHinhAnh.Text = danhMuc.HinhAnh;
            string saveLocation = MyFilePathHelper.GetImageFolderURL(this);
            this.imageDemons.Src = saveLocation + txtHinhAnh.Text;

            //load Album hinh
            LoadAlbumHinh(danhMuc.SanPhamID);
            //}
        }
    }
    private void LoadAlbumHinh(int sanpham)
    {
        string tmpPage = Request.QueryString["pg"];
        int currentPage = 1;
        if (tmpPage != null && tmpPage != "")
        {
            currentPage = Convert.ToInt32(tmpPage);
        }
        HinhAnhSanPhamDataSet spDs = new HinhAnhSanPhamHelper().LoadHinhAnhSanPhamTheoSanPham(sanpham);

        repSanPham.DataSource = spDs.HinhAnhSanPham;
        repSanPham.DataBind();

        TotalRecord = spDs.HinhAnhSanPham.Rows.Count;

        ResultCount.Text = TotalRecord.ToString();

        //Paging page = getPagingObject(TotalRecord, currentPage, PagingSize);

        //PageString = page.BuildPaging();
    }

    protected void bttThemMoi_OnClick(object sender, EventArgs e)
    {
        RedirectPage("ChiTietHinhAnhSanPham.aspx?mode=new&sanphamid="+Request.QueryString["id"],true);
    }

    protected void learnMoreButton_Click(object sender, EventArgs e)
    {
        int id = Convert.ToInt32(((Button)sender).CommandArgument);
        HinhAnhSanPhamDataSet bannerDs = new HinhAnhSanPhamHelper().LoadHinhAnhSanPham(id);
        bannerDs.HinhAnhSanPham[0].Delete();
        new HinhAnhSanPhamHelper().SaveHinhAnhSanPham(bannerDs);
        RedirectPage(Request.RawUrl, true);
    }

    protected void repSanPham_OnItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Button repCon = ((Button)e.Item.FindControl("learnMoreButton"));
            repCon.Attributes.Add("onclick", "if (!confirm('Xóa dữ liệu?')) return;");
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        this.RedirectLastVisitedPage();
    }

    private void SaveData()
    {
        try
        {
            string mode = Request.QueryString["mode"];
            m_SanPhamDataSet = (SanPhamDataSet)Session[this.Request.Url.AbsolutePath.ToString() + "_" + "Data"];
            //SetViewMode(canEdit);
            SanPhamDataSet.SanPhamRow danhMuc = m_SanPhamDataSet.SanPham[0];

            danhMuc.TenSanPham = txtTenSanPham.Text;
            danhMuc.LoaiSanPham = Convert.ToInt32(ddlLoaiCon.SelectedValue);
            danhMuc.HangSanXuat = txtHangSanXuat.Text;
            danhMuc.ChungLoai = txtChungLoai.Text;
            danhMuc.Gia = Convert.ToInt32(txtGia.Text);
            UploadImage();
            if (txtHinhAnh.Text == string.Empty)
            {
                txtHinhAnh.Text = "noimage.jpg";
            }
            danhMuc.HinhAnh = txtHinhAnh.Text;
            danhMuc.SanPhamMoi = ckSanPhamMoi.Checked;
            if (txtThuTu.Text!="") danhMuc.ThuTu = Convert.ToInt32(txtThuTu.Text);
            danhMuc.NgayDang = DateTime.Now;

            danhMuc.TongQuan = txtTongQuan.Text;
            danhMuc.ThongSoKyThuat = txtThongSo.Text;
            danhMuc.Album = txtAlbum.Text;

            SanPhamHelper helper = new SanPhamHelper();
            helper.SaveSanPham(m_SanPhamDataSet);
        }
        catch (Exception ex)
        {
            //DisplayMesseage(ex.Message);
            this.RedirectPage("pgError.aspx", false);
        }
        this.RedirectPage("QuanLySanPham.aspx?id="+Convert.ToInt32(Request.QueryString["loaicha"]), false);
    }

    private void UploadImage()
    {
        if (chkDeleteFile.Checked && txtHinhAnh.Text != string.Empty)
        {
            //delete old image
            try
            {
                string saveLocation = MyFilePathHelper.GetImageFolderURL_Saving(this);
                MyFilePathHelper.DeleteResource(saveLocation, txtHinhAnh.Text);
            }
            catch (Exception)
            {
            }
            finally
            {
                txtHinhAnh.Text = "noimage.jpg";
            }
            //postpone new image
        }
        //save new image
        if (this.inputFile.PostedFile != null && this.inputFile.PostedFile.ContentLength > 0)
        {
            string fn = System.IO.Path.GetFileName(inputFile.PostedFile.FileName);
            string path = MyFilePathHelper.GetImageFolderURL_Saving(this);
            fn = MyFilePathHelper.AppendTimeStamp(fn);
            string saveLocation = path  + fn;

            inputFile.PostedFile.SaveAs(saveLocation);
            FileStream fs = File.Open(saveLocation, FileMode.Open, FileAccess.Read);
            byte[] inByte = new byte[fs.Length];
            fs.Read(inByte, 0, inByte.Length);
            fs.Close();
            MyFilePathHelper.DeleteResource(path , fn);
            ImagesConvertHelper iconvert = new ImagesConvertHelper();
            string filename;
            if (iconvert.ConvertImage(saveLocation, inByte, 6, out filename) == false)
                txtHinhAnh.Text = string.Empty;
            else
            {
                txtHinhAnh.Text =   fn + ".JPG";
            }
        }
    }
}